import router from '@/router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import pinia from '@/stores'
import { useUserStore } from './stores/userstore'
import { showToast } from 'vant'
import nProgress from 'nprogress'
const userstore = useUserStore(pinia)
const whitelist = [
	'/login',
	'/',
	'/category',
	'/worthbuy',
	'/register',
	'/search',
	'/goods',
	'/prodlist',
	'/proddetail'
]
router.beforeEach((to, from, next) => {
	NProgress.start()
	const token = userstore.token
	if (token) {
		if (to.path === '/login') {
			NProgress.done()
			next({ path: '/' })
		} else {
			if (userstore.userInfo.id) {
				NProgress.done()
				next()
			} else {
				try {
					userstore.getuserinfo()
					NProgress.done()
					next()
				} catch (error) {
					userstore.reset()
					showToast('登录信息过期，请重新登录')
					NProgress.done()
					next({ path: '/login' })
				}
			}
		}
	} else {
		if (whitelist.includes(to.path)) {
			next()
			nProgress.done()
		} else {
			next({ path: '/login' })
			nProgress.done()
		}
	}
})
router.afterEach(() => {
	nProgress.done()
})
